#include "deactivatewidget.h"
#include "ui_deactivatewidget.h"
#include <QGSettings>
#include <QMessageBox>
#include <QSettings>
#include <QHostInfo>

DeactivateWidget::DeactivateWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DeactivateWidget)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint);
    this->setProperty("useStyleWindowManager",false);

//    if(QGSettings::isSchemaInstalled(QString("org.ukui.style").toLocal8Bit()))
//    {
//        QGSettings* gsetting=new QGSettings(QString("org.ukui.style").toLocal8Bit(),QByteArray(),this);
//        if(gsetting->keys().contains("styleName"))
//        {
//            if(gsetting->get("style-name").toString()=="ukui-dark" || gsetting->get("style-name").toString()=="ukui-black")
//                ui->iconlabel->setPixmap(QPixmap(":/res/kylin-wihte.png"));
//            else
//                ui->iconlabel->setPixmap(QPixmap(":/res/kylin.png"));
//            connect(gsetting,&QGSettings::changed,[=](const QString &key){
//                if(key=="styleName")
//                {
//                    if(gsetting->get("style-name").toString()=="ukui-dark" || gsetting->get("style-name").toString()=="ukui-black")
//                        ui->iconlabel->setPixmap(QPixmap(":/res/kylin-wihte.png"));
//                    else
//                        ui->iconlabel->setPixmap(QPixmap(":/res/kylin.png"));
//                }
//            });
//        }
//    }

    deactivate_init();
//    tcpSocket=new QTcpSocket;
    this->tcpSocket = socketmanager::GetInstance()->get_tcpSocket();
    connect(tcpSocket,&QTcpSocket::readyRead,this,[=]{
        QByteArray buf=tcpSocket->readAll();
        qDebug()<<"tcp recv:"<<QString::fromLocal8Bit(buf);
        if(!buf.isEmpty())
        {
            QStringList list=QString::fromLocal8Bit(buf).split(":");
            if(list.at(0)=="KY-DEACTIVATE-STATUS" && list.size()==2)
            {
                errorText.clear();
                if(list.at(1)=="SUCCESS")//取消激活
                {
                    if(remove_activation_file())
                    {
                        exit_service();
                        errorText=tr("Deactivation successs!");
                    }
                    else
                    {
                        errorText=tr("Deactivation fail!");
                    }
                }
                else if(list.at(1)=="REJECTED")
                    errorText=tr("The administrator refused!");
                else if(list.at(1)=="PENDING")
                {
                    errorText=tr("Requires an administrator to confirm!");
                    //发送取消激活确认
//                    int port = 7070;
//                    QString serialNumber = get_serial_number();
//                    QStringList* strlist = new_register_number(serialNumber.toLocal8Bit().data());
//                    QString registerNumber = strlist->at(0);
//                    QString tcpSendInfo = "KY-DEACTIVATE:" + serialNumber + ":" + registerNumber;
////                    this->tcpSocket->abort();
//                    if (this->tcpSocket->state()!=QAbstractSocket::UnconnectedState)
//                        this->tcpSocket->disconnectFromHost();
//                    this->tcpSocket = socketmanager::GetInstance()->get_tcpSocket();
//                    this->tcpSocket->connectToHost(serverip,port);
//                    if(!this->tcpSocket->waitForConnected(15000)) {
////                        qDebug() << "Can't connect to host: "<<this->tcpSocket->error();
////                        return ;
//                    }
//                    this->tcpSocket->write(tcpSendInfo.toLatin1());
//                    this->tcpSocket->flush();
                }

                if(!errorText.isEmpty())
                {
                    QMessageBox *box=new QMessageBox(QMessageBox::Warning, NULL, errorText,QMessageBox::NoButton,this);
                    QPushButton *closeButton = box->addButton(tr("Close"), QMessageBox::AcceptRole);
                    box->setDefaultButton(closeButton);
                    box->exec();
                    delete box;
                }
            }
        }
    });
}

DeactivateWidget::~DeactivateWidget()
{
    delete tcpSocket;
    delete ui;
}

void DeactivateWidget::disconnect_any_signal()
{
    disconnect(tcpSocket,&QTcpSocket::readyRead,this,0);
}

void DeactivateWidget::deactivate_init()
{
    QSettings settings("/etc/kylin-activation/activation_conf.ini", QSettings::IniFormat);
    QString server_dns = settings.value("KMS_Activation/ServerIp").toString();
    this->server_dns.clear();
    //同步查找服务端ip,可能造成界面弹出延迟
    QHostInfo host = QHostInfo::fromName(server_dns);
    if (host.error() != QHostInfo::NoError) {
        qDebug() << "DeactivateWidget Lookup failed:" << host.errorString();
        return;
    }
    Q_FOREACH(QHostAddress address, host.addresses()) {
        this->server_dns = address.toString();
        qDebug() << "DeactivateWidget Found address:" << this->server_dns;
        break;
    }
}

void DeactivateWidget::paintEvent(QPaintEvent *event)
{
    Interface interface;
    interface.setFontSize(ui->label);
}

void DeactivateWidget::on_returnbtn_clicked()
{
    emit returnSignal();
}

void DeactivateWidget::getServerInfo(int type,QHostAddress serverip)
{
    if(type==0)
    {
        QMessageBox *box=new QMessageBox(QMessageBox::Warning, NULL, tr("No quota, please contact the administrator!"),QMessageBox::NoButton,this);
        QPushButton *closeButton = box->addButton(tr("Close"), QMessageBox::AcceptRole);
        box->setDefaultButton(closeButton);
        box->exec();
        delete box;
    }

    this->serverip=serverip;
}

void DeactivateWidget::on_activebtn_clicked()
{
    int port = 7070;
//    this->tcpSocket->connectToHost(serverip,port);
    QString serialNumber = get_serial_number();
    QStringList* strlist = new_register_number(serialNumber.toLocal8Bit().data());
    QString registerNumber = strlist->at(0);
    QString tcpSendInfo = "KY-DEACTIVATE:" + serialNumber + ":" + registerNumber + ":" + QString::fromLocal8Bit(ui->textEdit->toPlainText().toLocal8Bit().toBase64());
//    this->tcpSocket->abort();
    if (this->tcpSocket->state()!=QAbstractSocket::UnconnectedState)
        this->tcpSocket->disconnectFromHost();
    this->tcpSocket = socketmanager::GetInstance()->get_tcpSocket();
    this->tcpSocket->connectToHost(this->serverip,port);
    if(!this->tcpSocket->waitForConnected(15000)) {
        qDebug() << "Can't connect to host: "<<this->tcpSocket->error();
        return ;
    }
    this->tcpSocket->write(tcpSendInfo.toLatin1());
    this->tcpSocket->flush();
    qDebug()<<"tcp send:"<<tcpSendInfo;
}
